package com.socket.client.handler.command.impl;

import com.socket.client.handler.command.CommandHandler;
import com.socket.client.handler.command.anno.Command;
import com.socket.client.manager.AuthnManager;
import com.socket.client.manager.GroupManager;
import com.socket.client.manager.UserManager;
import com.socket.client.model.base.BaseUser;
import com.socket.client.model.chat.ChatUser;
import com.socket.client.util.CommandUtil;
import com.socket.core.model.command.enmus.Authn;
import com.socket.core.model.command.topic.AuthnTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

/**
 * 权限命令处理基础类
 */
@Slf4j
public abstract class AuthnCommand implements CommandHandler<AuthnTopic, Authn> {
    @Autowired
    protected AuthnManager authnManager;
    @Autowired
    protected GroupManager groupManager;
    @Autowired
    protected UserManager userManager;

    @Override
    public boolean invoke(AuthnTopic topic) {
        if (support(topic)) {
            log.debug("ParseCommand: {}, Pointer: {}", topic.getOperation(), getClass().getName());
            ChatUser self = Optional.ofNullable(topic.getSelf())
                    .map(userManager::getUser)
                    .orElse(null);
            BaseUser target = Optional.ofNullable(topic.getTarget())
                    .map(e -> authnManager.getBaseUser(e))
                    .orElse(null);
            this.invoke(self, target, topic.getParam());
            return true;
        }
        return false;
    }

    @Override
    public boolean support(AuthnTopic topic) {
        return CommandUtil.support(topic.getOperation(), getClass(), Command.Authn.class, Command.Authn::value);
    }

    public abstract <T> void invoke(ChatUser self, BaseUser target, T param);
}
